package com.pureut.system.service.impl;

import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.StringUtils;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.domain.MaterialCoding;
import com.pureut.system.domain.MaterialHalf;
import com.pureut.system.domain.SysTheAlarm;
import com.pureut.system.domain.dto.MaterialHalfDto;
import com.pureut.system.domain.dto.MaterialMqDto;
import com.pureut.system.domain.dto.ProjectRecursionDto;
import com.pureut.system.domain.vo.MaterialAlarmVo;
import com.pureut.system.domain.vo.MaterialHalfVo;
import com.pureut.system.export.MaterialHalfExport;
import com.pureut.system.mapper.MaterialBomHalfMapper;
import com.pureut.system.mapper.MaterialCodingMapper;
import com.pureut.system.mapper.MaterialHalfMapper;
import com.pureut.system.mapper.SysTheAlarmMapper;
import com.pureut.system.service.IMaterialHalfService;
import com.pureut.system.util.MaterialMqUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 半成品实现类
 * @Param
 * @Date 22-11-25
 * @Author hl
 **/
@Service
public class MaterialHalfServiceImpl implements IMaterialHalfService {

    @Resource
    private MaterialHalfMapper materialHalfMapper;

    @Resource
    private SysTheAlarmMapper sysTheAlarmMapper;

    @Resource
    private MaterialAwmateriaServiceImpl materialAwmateriaServiceImpl;

    @Resource
    private MaterialCodingMapper materialCodingMapper;

    @Resource
    private SysMidSplitServiceImpl sysMidSplitServiceImpl;

    @Resource
    private MaterialBomHalfMapper materialBomHalfMapper;

    /**
     * 查询半成品信息
     *
     * @param materialHalf 半成品信息
     * @return 半成品集合
     */
    @Override
    @DataScope(deptAlias = "t1")
    public List<MaterialHalfDto> selectHalfList(MaterialHalfVo materialHalf) {
        List<SysDictData> netArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<MaterialHalfDto> list = materialHalfMapper.selectHalfList(materialHalf);
        for (MaterialHalfDto dto :
                list) {
            dto.setMaterialUnitDict(netMap.get(String.valueOf(dto.getMaterialUnit())));
            dto.setBomType("3");
            dto.setBomTypeDict("半成品");
        }
        return list;
    }

    /**
     * 新增半成品信息
     *
     * @param materialHalf 半成品信息
     * @return 半成品集合
     */
    @Override
    public int insertMaterialHalf(MaterialHalf materialHalf) throws Exception {
        materialHalf.setDeptId(SecurityUtils.getDeptId());
        materialHalf.setMaterialCode(sysMidSplitServiceImpl.splitStr(materialCodingMapper.selectCodingTypeThe(materialHalf.getMaterialType())));
        materialHalf.setCreateBy(SecurityUtils.getUsername());
        int ins = materialHalfMapper.insertMateriaHalf(materialHalf);
        if (ins > 0) {
            if (materialHalf.getAlarmCode()!=null) {
                List<SysTheAlarm> list = materialAwmateriaServiceImpl.alarmConfiguration(materialHalf.getAlarmCode());
                long op = materialHalf.getMaterialId();
                String matetialCode = materialHalf.getMaterialCode();
                for (SysTheAlarm sysTheAlarm :
                        list) {

                    String roles = "";
                    for (int i = 0; i < sysTheAlarm.getRoleIds().size(); i++) {

                        roles = roles + sysTheAlarm.getRoleIds().get(i);
                        if (sysTheAlarm.getRoleIds().size()-1!=i){
                            roles = roles + ",";
                        }

                    }

                    sysTheAlarm.setAlarmRoleId(roles);

                    sysTheAlarm.setAlarmAssociatedId(op);
                    sysTheAlarm.setAlarmOfMaterial(3);
                    sysTheAlarm.setAlarmMaterialCode(matetialCode);
                }
                if (list.size()!=0){
                    ins = sysTheAlarmMapper.insertSysTheAlarm(list);
                }

            }
            if (ins == 0) {
                throw new SQLException("抛出异常");
            }
            MaterialMqDto mq = new MaterialMqDto();
            mq.setMaterialCode(materialHalf.getMaterialCode());
            mq.setMaterialName(materialHalf.getMaterialName());
            mq.setMaterialSpec(materialHalf.getMaterialSpec());
            mq.setMaterialCategory(3);
            mq.setMaterialType(materialHalf.getMaterialType());
            mq.setMaterialRatio(materialHalf.getMaterialRatio());
            mq.setMaterialInspection(materialHalf.getMaterialInspection());
            mq.setMaterialUnit(String.valueOf(materialHalf.getMaterialUnit()));
            mq.setMaterialHair(materialHalf.getMaterialHair());
            mq.setMaterialClosed(materialHalf.getMaterialClosed());
            mq.setMaterialReminder(materialHalf.getMaterialReminder());//复检提醒
            mq.setMaterialQuality(materialHalf.getMaterialQuality());//保质期
            mq.setMaterialOverdue(materialHalf.getMaterialOverdue());//过期提醒
            mq.setMaterialMinSecurity(materialHalf.getMaterialMinSecurity());//最小安全库存

            MaterialMqUtil.materialMqSend(mq);
        }
        return ins;
    }

    /**
     * 删除半成品信息
     *
     * @param materialId 半成品信息
     * @return 半成品集合
     */
    @Override
    public int deleteMaterialHalf(String materialId) throws Exception {
        String[] materialIdS = materialId.split(",");
        //同步删除半成品信息
        MaterialMqDto mq = new MaterialMqDto();
        List<String> materialIdList = Arrays.asList(materialId.split(","));
        String materialHalfStr = materialHalfMapper.getMaterialHalfById(materialIdList);
        mq.setMaterialCode(materialHalfStr);
        //删除标识
        mq.setMark(3);
        MaterialMqUtil.materialMqSendDelete(mq);

        int is = materialHalfMapper.deleteMateriaHalfById(materialIdS);
        if (is > 0) {
            sysTheAlarmMapper.deleteSysTheAlarmById(materialIdS);
            if (is == 0) {
                throw new SQLException("抛出异常");
            }
        }
        return is;
    }

    /**
     * 查询单个半成品信息
     * @param materialId 半成品信息
     * @return 半成品集合
     */
    @Override
    public MaterialHalfDto selectMaterialHalfById(long materialId) {
        MaterialHalfVo materialHalf = new MaterialHalfVo();
        materialHalf.setMaterialId(materialId);
        List<MaterialHalfDto> list = materialHalfMapper.selectHalfList(materialHalf);
        MaterialHalfDto materialHalfDto = new MaterialHalfDto();
        materialHalfDto = list.get(0);
        int alarmOfMaterial = 3;
        List<SysTheAlarm> theList = sysTheAlarmMapper.selectSysTheAlarmList(materialId, alarmOfMaterial);
        MaterialAlarmVo materialAlarmVo = materialAwmateriaServiceImpl.alarmConfigtType(theList);
        materialHalfDto.setAlarmCode(materialAlarmVo);
        return materialHalfDto;
    }

    /**
     * 修改半成品信息
     *
     * @param materialHalf 半成品信息
     * @return 半成品集合
     */
    @Override
    public int updatMaterialHalfEdit(MaterialHalf materialHalf) throws Exception {
        int ors = materialHalfMapper.updatMateriaHalfEdit(materialHalf);
        if (ors > 0) {
            long materialId = materialHalf.getMaterialId();
            sysTheAlarmMapper.deleteSysTheAlarmOnById(materialId);
            if (ors > 0) {
                long sy = materialHalf.getMaterialId();
                String materialCode = materialHalf.getMaterialCode();
                List<SysTheAlarm> list = materialAwmateriaServiceImpl.alarmConfiguration(materialHalf.getAlarmCode());
                for (SysTheAlarm sysTheAlarm :
                        list) {

                    String roles = "";
                    for (int i = 0; i < sysTheAlarm.getRoleIds().size(); i++) {

                        roles = roles + sysTheAlarm.getRoleIds().get(i);
                        if (sysTheAlarm.getRoleIds().size()-1!=i){
                            roles = roles + ",";
                        }

                    }

                    sysTheAlarm.setAlarmRoleId(roles);

                    sysTheAlarm.setAlarmAssociatedId(sy);
                    sysTheAlarm.setAlarmOfMaterial(3);
                    sysTheAlarm.setAlarmMaterialCode(materialCode);
                }
                if (list.size()!=0) {
                    ors = sysTheAlarmMapper.insertSysTheAlarm(list);
                }
                if (ors == 0) {
                    throw new SQLException("抛出异常");
                }
            } else {
                throw new SQLException("抛出异常");
            }
            MaterialMqDto mq = new MaterialMqDto();
            mq.setMaterialCode(materialHalf.getMaterialCode());
            mq.setMaterialName(materialHalf.getMaterialName());
            mq.setMaterialSpec(materialHalf.getMaterialSpec());
            mq.setMaterialCategory(3);
            mq.setMaterialType(materialHalf.getMaterialType());
            mq.setMaterialRatio(materialHalf.getMaterialRatio());
            mq.setMaterialInspection(materialHalf.getMaterialInspection());
            mq.setMaterialUnit(String.valueOf(materialHalf.getMaterialUnit()));
            mq.setMaterialHair(materialHalf.getMaterialHair());
            mq.setMaterialClosed(materialHalf.getMaterialClosed());
            mq.setMaterialReminder(materialHalf.getMaterialReminder());//复检提醒
            mq.setMaterialQuality(materialHalf.getMaterialQuality());//保质期
            mq.setMaterialOverdue(materialHalf.getMaterialOverdue());//过期提醒
            mq.setMaterialMinSecurity(materialHalf.getMaterialMinSecurity());//最小安全库存
            MaterialMqUtil.materialMqSend(mq);

            materialBomHalfMapper.updateBomInfo(materialHalf.getMaterialName(),materialHalf.getMaterialCode());
            materialBomHalfMapper.updateBomDetail(materialHalf.getMaterialName(),materialHalf.getMaterialCode());
        }
        return ors;
    }

    /**
     * 冻结/解冻
     *
     * @param materialHalf 半成品信息
     * @return 半成品集合
     */
    @Override
    public int updateMaterialHalfEditFreeze(MaterialHalf materialHalf) {
        return materialHalfMapper.updateHalfEditFreeze(materialHalf);
    }

    /**
     * 树结构
     *
     * @param
     * @return 半成品集合
     */
    @Override
    public List<ProjectRecursionDto> selectChildrenHalfListThe() {
        return MaterialAwmateriaServiceImpl.buildMenuTree(materialHalfMapper.selectChildrenHalfListThe());
    }

    /**
     * 根据物料编码查询详情（半成品信息）
     *
     * @param materialCode
     * @return
     */
    @Override
    public MaterialHalf selectMaterialHalfMaterialCode(String materialCode) {
        return materialHalfMapper.selectMaterialHalfMaterialCode(materialCode);
    }

    /**
     * 根据物料编码查询详情(委外订单明细列表fegin调用)
     * @param materialCode
     * @return
     */
    @Override
    public MaterialHalfDto getHalfViewByMaterialCode(String materialCode) {
        return materialHalfMapper.getHalfViewByMaterialCode(materialCode);
    }

    /**
     * 半成品导入
     * @param coCustomer
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importMouldData(List<MaterialHalfExport> coCustomer) {
        if (StringUtils.isNull(coCustomer) || coCustomer.size() == 0) {
            throw new GlobalException("导入半成品信息不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        //原料单位
        List<SysDictData> levelArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> levelMap = levelArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        for (MaterialHalfExport mouldModelExport : coCustomer) {
            MaterialHalf materialHalf = new MaterialHalf();
            try {
                if (mouldModelExport.getMaterialName() == null || mouldModelExport.getMaterialType() == null ) {
                    throw new GlobalException("存在必填字段为空,请核实");
                }

                materialHalf.setMaterialName(mouldModelExport.getMaterialName());

                //通过半成品类别名称查出原料类别id
                MaterialCoding materialCoding = materialCodingMapper.getMaterilTypeId(mouldModelExport.getMaterialType());

                if (materialCoding==null){
                    throw new GlobalException("不存在该原料类别导入失败");
                }
                materialHalf.setMaterialSpec(mouldModelExport.getMaterialSpec());
                materialHalf.setMaterialType((int) materialCoding.getCodingId());


                if (mouldModelExport.getMaterialQuality()!=null) {
                    materialHalf.setMaterialQuality(Integer.parseInt(mouldModelExport.getMaterialQuality()));
                }
                if (mouldModelExport.getMaterialOverdue()!=null){
                    materialHalf.setMaterialOverdue(Integer.parseInt(mouldModelExport.getMaterialOverdue()));
                }
                if (mouldModelExport.getMaterialInspection()!=null){
                    materialHalf.setMaterialInspection(Integer.parseInt(mouldModelExport.getMaterialInspection()));
                }
                if (mouldModelExport.getMaterialReminder()!=null){
                    materialHalf.setMaterialReminder(Integer.parseInt(mouldModelExport.getMaterialReminder()));
                }
                if (mouldModelExport.getMaterialMinSecurity()!=null){
                    materialHalf.setMaterialMinSecurity(Integer.parseInt(mouldModelExport.getMaterialMinSecurity()));
                }

                //原料单位
                for (Map.Entry<String, String> entry : levelMap.entrySet()) {
                    if (entry.getValue().equals(mouldModelExport.getMaterialUnit())) {
                        materialHalf.setMaterialUnit(Integer.parseInt(entry.getKey()));
                        break;
                    }
                }

                //超收标志
                if ("开".equals(mouldModelExport.getMaterialClosed())){
                    materialHalf.setMaterialClosed(1);
                }else{
                    materialHalf.setMaterialClosed(2);
                }
                if ("开".equals(mouldModelExport.getMaterialHair())){
                    materialHalf.setMaterialHair(1);
                }else{
                    materialHalf.setMaterialHair(2);
                }

                //打样标志
                if ("开".equals(mouldModelExport.getMaterialProofing())){
                    materialHalf.setMaterialProofing(1);
                }else{
                    materialHalf.setMaterialProofing(2);
                }

                //委外标志
                if ("开".equals(mouldModelExport.getMateriaOutsourcing())){
                    materialHalf.setMateriaOutsourcing(1);
                }else{
                    materialHalf.setMateriaOutsourcing(2);
                }

                int i = insertMaterialHalf(materialHalf);
                if (i==0){
                    throw new GlobalException("导入失败");
                }

                successNum++;
                successMsg.append(successNum).append("、半成品信息 ").append(mouldModelExport.getMaterialName()).append(" 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = failureNum + "、半成品名称 " + mouldModelExport.getMaterialName() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new GlobalException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }
}
